
// 引入WebSocket模块 npm install nodejs-websocket
var ws = require('nodejs-websocket')
var PORT = 1760  

var server = ws.createServer(function(conn){
    conn.on("text",function(str){
        console.log(str)
        let data = JSON.parse(str)
        switch(data.type){
            case "setUser":
                conn.userId = data.userId
                break;
            case "sendTo":
                sendTo(data.userId,data.msg)
                break;
            case "pageTo": //跳转页面 指令
                sendTo(data.userId,data.msg)
                break;
        }
    })
    conn.on("close",function(code,reason){
        server.connections.forEach(conn=>{
            console.log(conn.userId)
        })
        console.log("当前连接数",server.connections.length)
    })
    conn.on("error",function(err){
        console.log("handle err")
        console.log(err)
    })
}).listen(PORT)

//创建 发送 指定 信息 方法
const sendTo = (userId,data)=>{
    server.connections.forEach(conn=>{
        if(conn.userId == userId){
            conn.sendText(data)
        }
    })
    console.log(server.connections.length)
}

console.log('websocket server listening on port ' + PORT)